package com.zhixi100.userservice.service;

import com.zhixi100.framework.utils.CookieUtils;
import com.zhixi100.userservice.entity.User;
import com.zhixi100.userservice.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * author:tommy
 * date:2018/12/8
 */
@Service
public class UserService {

    private final String PRE_TOKEN = "user:jsessionid:";

    @Autowired
    private RedisTemplate redisTemplate;


    @Autowired
    private UserMapper userMapper;

    public User findUserByUserName(String userName) {
        return userMapper.findUserByUserName(userName);
    }

    public User checkUser(User user) {
        return userMapper.checkUser(user);
    }

    public int login(User user, HttpServletRequest request, HttpServletResponse response) {
        User u = userMapper.checkUser(user);
        int res = 0;
        if (u != null) {
            String token = UUID.randomUUID().toString().replaceAll("-", "");
            String sessionid = request.getSession().getId();
            System.out.println(sessionid + "-------------------");

            final Map<String, Object> properties = new HashMap();
            properties.put("id", String.valueOf(u.getId()));
            properties.put("name", u.getUserName());
            properties.put("mobile", u.getMobile());

            //写到Redis中
            //redisTemplate.opsForValue().set(PRE_TOKEN + token, properties, 30, TimeUnit.MINUTES);

            //写到cookie中
            //CookieUtils.setCookie(response, "jsessionid", token, "/api", 30 * 60);

            //使用spring session
            HttpSession session = request.getSession();
            session.setAttribute("user", properties);

            res = 1;
        }
        return res;
    }


}
